//
//  CYCollectionVC.m
//  CreditAddressBook
//
//  Created by Lee on 15/9/9.
//  Copyright (c) 2015年 Lee. All rights reserved.
//

#import "CYCollectionVC.h"
#import "CYCollectTool.h"
#import "CYCallRecord.h"
#import "CYCallRecordCVCell.h"
#import <AddressBookUI/AddressBookUI.h>
#import "CYABTool.h"
#import "CYDialTool.h"
#import "UIInfomationView.h"
#import "CYCollectionMenu.h"
#import "CYABDetailVController.h"
#import "CYDatabase.h"
#import "CYCollection.h"
#import "CYABDetailPageVC.h"
#import "CYICollectionViewFlowLayout.h"
#import "MBProgressHUD+MJ.h"
#import "CYCallCenter.h"

#define isSuccess _collection && _collection.count && indexPath.row < _collection.count
static NSString *const _ID = @"collectionCell";

@interface CYCollectionVC ()<UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout, ABPeoplePickerNavigationControllerDelegate>

@property(nonatomic, strong) UICollectionView *collectionView;
@property(nonatomic, strong) NSArray *collection;//处理后的显示数据
@property(nonatomic, strong) ABPeoplePickerNavigationController *picker;
@property(nonatomic, strong) NSArray *collectionItems;

@property (nonatomic ,strong) NSArray *collections;//数据库读取数据

@property(nonatomic, assign) CGFloat cellW;//cell的宽
@property(nonatomic, assign) CGFloat cellH;//cell的高
@end

@implementation CYCollectionVC

- (NSArray *)collections {
    if (!_collections) {
        _collections = [[CYDatabase sharedDatabase] collections];
    }
    return _collections;
}

- (NSArray *)collectionItems {
    if (!_collectionItems) {
        _collectionItems = [CYCollectTool sharedCollectTool].collectedDeals;
    }
    return _collectionItems;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupCollectionView];
//    [self loadData];
    [self loadDataFromDB];
    [self setupNotification];
}

- (void)setupCollectionView {
    CYICollectionViewFlowLayout *layout = [[CYICollectionViewFlowLayout alloc] init];
//    九宫格老写法
//    //列数
//    int cols = 3;
//    CGFloat width = CYScreeSize.width;
//    //cell宽度
//    CGFloat cellW = (width - 2 * 30)/cols;
//    self.cellW = cellW+320;
//    //cell高度
//    self.cellH = cellW + 20;
//    // cell的大小
//    layout.itemSize = CGSizeMake(cellW, self.cellH);
    
    //cell宽度
    self.cellW = self.view.width;
    //cell高度
    self.cellH = 65;
    // cell的大小
    layout.itemSize = CGSizeMake(self.view.width, 65);
    
    
    self.collectionView = [[UICollectionView alloc] initWithFrame:self.view.frame collectionViewLayout:layout];
    self.collectionView.collectionViewLayout = layout;
    self.collectionView.alwaysBounceVertical = YES;
    [self.view addSubview:self.collectionView];
    self.collectionView.backgroundColor = CYColor(239, 239, 244, 1);
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    
    [CYCallRecordCVCell collectionView:self.collectionView registerCellWithReuseIdentifier:_ID];
    //160为添加到首页后头部导航加底部导航的高度
    self.collectionView.contentInset = UIEdgeInsetsMake(4, 16, 160, 16);
    self.collectionView.showsVerticalScrollIndicator = NO;
}

- (void)loadData {
    NSMutableArray *b = [NSMutableArray array];
    for (CYCollectItem *item in self.collectionItems) {
        CYCallRecord *callRecord = [[CYCallRecord alloc]init];
        CYCallHistory *his = [[CYCallHistory alloc]init];
        his.phone = item.phone;
        his.name = item.name;
        his.thumbnail =item.thumbnailLocal;
        callRecord.callHistory = his;
        callRecord.callHistory.headImageName = item.headImageName;
        callRecord.showTimesImageView = NO;
        [b addObject:callRecord];
    }
    self.collection = b;
}

- (void)loadDataFromDB {
    RHAddressBook *addressbook = [CYABTool addressBook];
    
    NSMutableArray *b = [NSMutableArray array];
    for (CYCollection *item in self.collections) {
        CYCallRecord *callRecord = [[CYCallRecord alloc]init];
        CYCallHistory *his = [[CYCallHistory alloc]init];
        his.phone = item.phone;
        his.name = item.name;
//        his.thumbnail =item.thumbnailLocal;
        if (item.recordId) {
            RHPerson *person = [addressbook personForABRecordID:(ABRecordID)item.recordId.integerValue];
            his.thumbnail = person.thumbnail;
        }
        callRecord.callHistory = his;
        callRecord.callHistory.headImageName = item.headimageName;
        callRecord.showTimesImageView = NO;
        [b addObject:callRecord];
        //测试
//        [b addObject:callRecord];
    }
    self.collection = b;
}

/**
 *  更新数据缓存
 */
- (void)updateCollectItems {
//    self.collectiontems = nil;
    self.collections = nil;
//    [self loadData];
    [self loadDataFromDB];
    [self.collectionView reloadData];
}

- (void)setupNotification {
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(addCollection:) name:CYCollectionNotification object:nil];
}

/**
 *  收藏监听
 */
- (void)addCollection:(NSNotification *)noti {
    [self updateCollectItems];
}

#pragma mark - collectionDelegate
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.collection.count + 1;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    CYCallRecordCVCell *cell = [CYCallRecordCVCell collectionView:collectionView dequeueReusableCellWithReuseIdentifier:_ID forIndexPath:indexPath];
    
    if (isSuccess) {
        cell.cellH = self.cellH;
        CYCallRecord *call = self.collection[indexPath.row];
        call.dataType = CYCallRecordTypeCollectionData;
        call.indexPath = indexPath;
        cell.style = CYCallRecordCellStyleDefault;
        cell.callRecord = call;
        [cell detailBtnAddTarget:self action:@selector(detailBtnClick:)];
    } else {
        cell.style = CYCallRecordCellStyleAdd;
    }
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    @try {
        if (isSuccess) {
            //        CYCollectItem *item = self.collectionItems[indexPath.row];
            CYCollection *item = self.collections[indexPath.row];
            CYCallRecord *call = self.collection[indexPath.row];
            if (!call.person) {
                RHAddressBook *addressbook = [CYABTool addressBook];
                RHPerson *person = [addressbook personForABRecordID:(ABRecordID)item.recordId.integerValue];
                call.person = [[CYPerson alloc] initWithRHPerson:person];
            }
            [[CYCallCenter sharedCallCenter] callWithNumber:call.callHistory.phone name:call.callHistory.name person:call.person success:^{
                //通知更新通话记录
                [CYNotificationCenter postNotificationName:CYDialNotification object:nil userInfo:nil];
            } failure:^{
                CYLog(@"保存通话记录失败");
            }];
        } else {
            self.picker = [[ABPeoplePickerNavigationController alloc] init];
            self.picker.peoplePickerDelegate = self;
            [self presentViewController:self.picker animated:YES completion:nil];
        }
    }
    @catch (NSException *exception) {
        [MBProgressHUD showError:@"通话失败"];
    }
}

/**
 *  头部点击
 */
- (void)detailBtnClick:(UIButton *)btn {
//    CGFloat x = (self.cellW + 10) * (btn.tag % 3 + 1);
//    CGFloat y = 10 * (btn.tag / 3 + 1) + self.cellH * (btn.tag / 3);
//    [CYCollectionMenu showInView:self.view targetRect:CGPointMake(x, y) clickAtIndex:^(NSInteger buttonIndex) {
//        if (buttonIndex == CYIndexFirst) {//详情
//            [self detailAction:btn];
//        } else if (buttonIndex == CYIndexSecond) {//删除
//            [self deleteAction:btn];
//        }
//    }];
    CYCallRecord *call = self.collection[btn.tag];
    CYCollection *item = self.collections[btn.tag];
    CYPerson *cyperson = call.person;
    if (!cyperson) {
        RHAddressBook *addressbook = [CYABTool addressBook];
        RHPerson *person = [addressbook personForABRecordID:(ABRecordID)item.recordId.integerValue];
        if (person) {
            cyperson = [[CYPerson alloc] initWithRHPerson:person];
            cyperson.pushTag = 1;
            cyperson.segmentTag = 5;
            cyperson.add = NO;
            call.person = cyperson;
        }
    }
    CYABDetailPageVC *detail = [[CYABDetailPageVC alloc] initWithPerson:cyperson andCallRecord:call defrId:nil];
    detail.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:detail animated:YES];
}

- (void)detailAction:(UIButton *)btn {
    CYCallRecord *call = self.collection[btn.tag];
    CYCollection *item = self.collections[btn.tag];
    CYPerson *cyperson = call.person;
    if (!cyperson) {
        RHAddressBook *addressbook = [CYABTool addressBook];
        RHPerson *person = [addressbook personForABRecordID:(ABRecordID)item.recordId.integerValue];
        if (person) {
            cyperson = [[CYPerson alloc] initWithRHPerson:person];
            cyperson.pushTag = 1;
            cyperson.segmentTag = 5;
            cyperson.add = NO;
            call.person = cyperson;
        } else {
            //删除该收藏
            [[CYDatabase sharedDatabase] deleteCollectionWithPhoneNum:item.phone];
            [self updateCollectItems];
            return;
        }
    }
    
    CYABDetailPageVC *detail = [[CYABDetailPageVC alloc] initWithPerson:cyperson andCallRecord:call defrId:nil];
    detail.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:detail animated:YES];
}

- (void)deleteAction:(UIButton *)btn {
//    CYCollectItem *item = self.collectionItems[btn.tag];
    CYCollection *item = self.collections[btn.tag];
//    [[CYCollectTool sharedCollectTool] uncollectItem:item];
    [[CYDatabase sharedDatabase] deleteCollectionWithId:item.collectionId];
    [self updateCollectItems];
}

#pragma mark - ABPeoplePickerNavigationController 代理
/**
 *  ios8前调用该方法
 */
- (BOOL)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker shouldContinueAfterSelectingPerson:(ABRecordRef)person {
    [self.picker dismissViewControllerAnimated:YES completion:nil];
    
    RHAddressBook *addressBook = [CYABTool addressBook];
    RHPerson *rhperson = [addressBook personForABRecordRef:person];
    [self collectionWithPerson:rhperson];
    return NO;
}

- (void)peoplePickerNavigationControllerDidCancel:(ABPeoplePickerNavigationController *)peoplePicker {
    [self.picker dismissViewControllerAnimated:YES completion:nil];
}

/**
 *  ios8后调用该方法
 */
- (void)peoplePickerNavigationController:(ABPeoplePickerNavigationController*)peoplePicker didSelectPerson:(ABRecordRef)person {
    
    RHAddressBook *addressBook = [CYABTool addressBook];
    RHPerson *rhperson = [addressBook personForABRecordRef:person];
    [self collectionWithPerson:rhperson];
}

/**
 *  收藏
 */
- (void)collectionWithPerson:(RHPerson *)person {
    if (person.phoneNumbers.values.count) {
//        CYCollectItem *item = [[CYCollectItem alloc]init];
        CYCollection *item = [[CYCollection alloc] init];
        item.phone = person.phoneNumbers.values.firstObject;
        item.name = person.name ;
//        item.thumbnailLocal  = person.thumbnail;
        item.recordId = [NSString stringWithFormat:@"%@", @(person.recordID)];
//        [[CYCollectTool sharedCollectTool] collectItem:item];
        NSArray *totle = [[CYDatabase sharedDatabase] collectionWithRecordId:item.recordId];
        if (totle.count == 0) {
            BOOL result = [[CYDatabase sharedDatabase] addCollection:item];
            if (result) {
                [self updateCollectItems];
            } else {
                CYLog(@"收藏添加失败");
            }
        }
    }
}

- (void)dealloc {
    [CYNotificationCenter removeObserver:self];
}
@end
